# -*- coding: utf-8 -
# Copyright 2008 by Benoît Chesneau <benoitc@e-engura.com>
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from couchdb_django.client import Server
from django.conf import settings
from django.core.management.base import NoArgsCommand
import os
from optparse import make_option


class Command(NoArgsCommand):
    option_list = NoArgsCommand.option_list + (
        make_option('--verbosity', action='store', dest='verbosity', default='1',
            type='choice', choices=['0', '1', '2'],
            help='Verbosity level; 0=minimal output, 1=normal output, 2=all output'),)
    help = "Synchronize views in couchdb"
    
    def handle_noargs(self, **options):
        verbosity = int(options.get('verbosity', 1))
        
        couchdb_server = Server(settings.COUCHDB_URI)
        try:
            db = couchdb_server.create(settings.COUCHDB_DATABASE)
        except:
            db = couchdb_server[settings.COUCHDB_DATABASE]
        
        if verbosity >= 1:
            print "\nLoad CouchDB views ..."
        for app in settings.INSTALLED_APPS:
            appdir = os.path.dirname(__import__(app, {}, {}, ['']).__file__)
            design_path = os.path.join(appdir, '_design')
            if os.path.exists(design_path):
                for name in os.listdir(design_path):
                    path = os.path.join(design_path,name)
                    views = {}
                    for view in os.listdir(path):
                        views[view] = {}
                        for js in glob(os.path.join(path, view, '*.js')):
                            if os.path.basename(js) == 'map.js':
                                views[view]['map'] = load_file(js)
                            if os.path.basename(js) == 'reduce.js':
                                views[view]['reduce'] = load_file(js)
                        if verbosity >= 2:
                            print "add %s/%s" % (name, view)
                    try:
                        db['_design/%s' % name] = {
                            'language': 'javascript',
                            'views': views
                        }
                    except:
                        v = db['_design/%s' % name] 
                        v['views'] = views
                        db['_design/%s' % name] = v